package org.redpig.mimall.controller;

import lombok.extern.slf4j.Slf4j;
import org.redpig.mimall.consts.MimallConsts;
import org.redpig.mimall.form.UserLoginForm;
import org.redpig.mimall.form.UserRegisterForm;
import org.redpig.mimall.pojo.User;
import org.redpig.mimall.service.IUserService;
import org.redpig.mimall.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Objects;

import static org.redpig.mimall.enums.ResponseEnum.*;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private final IUserService userService;

    @Autowired
    public UserController(IUserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public ResponseVo<User> register(@Valid @RequestBody UserRegisterForm userRegisterForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("注册错误：{} {}", Objects.requireNonNull(bindingResult.getFieldError()).getField(),
                    bindingResult.getFieldError().getDefaultMessage());
            return ResponseVo.error(PARAM_ERROR, bindingResult);
        }

        User user = new User();
        BeanUtils.copyProperties(userRegisterForm, user);
        return userService.register(user);
    }

    @PostMapping("/login")
    public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userLoginForm, BindingResult bindingResult,
                                  HttpSession httpSession) {
        if (bindingResult.hasErrors()) {
            return ResponseVo.error(PARAM_ERROR, bindingResult);
        }

        ResponseVo<User> responseVo = userService.login(userLoginForm.getUsername(), userLoginForm.getPassword());

        //设置Session
        httpSession.setAttribute(MimallConsts.CURRENT_USER, responseVo.getData());
        log.info("session id={}", httpSession.getId());

        return responseVo;
    }

    //session保存在内存里，服务重启后将丢失
    //所以必须采用token+redis的方式
    @GetMapping
    public ResponseVo<User> obtainUserinfo(HttpSession httpSession) {
        User user = (User) httpSession.getAttribute(MimallConsts.CURRENT_USER);
        return ResponseVo.success(user);
    }

    /**
     * {@link TomcatServletWebServerFactory}getSessionTimeoutInMinutes
     * 如果设置时间间小于1分钟，就不生效
     */
    @PostMapping("/logout")
    public ResponseVo<User> logout(HttpSession httpSession) {
        httpSession.removeAttribute(MimallConsts.CURRENT_USER);
        return ResponseVo.success();
    }
}
